package com.work.service.main.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.work.constant.ExceptionDescription;
import com.work.dto.transport.TransportSearchDTO;
import com.work.entity.main.TShipForecast;
import com.work.mapper.main.TShipForecastMapper;
import com.work.service.main.ITShipForecastService;
import com.work.service.transport.ITransportService;
import com.work.vo.main.TShipForecastVO;
import com.work.vo.transport.TShipForecastShipStatVO;
import com.work.vo.transport.TransportShipVO;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 理货船舶预报接口实现
 *
 * @author ：dujianyu
 * @since ：Created in 2024/3/12 14:28
 */
@Service
@AllArgsConstructor
public class TShipForecastServiceImpl extends BaseServiceImpl<TShipForecastMapper, TShipForecast> implements ITShipForecastService {

    private ITransportService transportService;


    @Override
    public boolean addShipForecast(Long transportShipId) {
        if (isTransportShipIdExist(transportShipId)) {
            return true;
        }

        TransportSearchDTO transportSearchDTO = new TransportSearchDTO();
        transportSearchDTO.setTransportShipId(transportShipId);
        TransportShipVO transportShip = transportService.selectTransportShip(transportSearchDTO);

        if (Func.isNull(transportShip)) {
            throw new RuntimeException(ExceptionDescription.DB_ERROR + "货运系统无该船信息");
        }

        TShipForecast entity = BeanUtil.copy(transportShip, TShipForecast.class);
        return super.saveOrUpdate(entity);
    }

    @Override
    public TShipForecastVO selectDetail(String transportShipId) {
        return baseMapper.selectDetail(Func.toLong(transportShipId));
    }

    @Override
    public IPage<TShipForecastShipStatVO> selectTransportShipListForShipStatPage(IPage<TShipForecastShipStatVO> page, TransportSearchDTO dto) {
        List<TShipForecastShipStatVO> data = baseMapper.selectTransportShipListForShipStatList(dto, page);
        return page.setRecords(data);
    }

    private boolean isTransportShipIdExist(Long transportShipId) {
        QueryWrapper<TShipForecast> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(TShipForecast::getId)
                .eq(TShipForecast::getIsDeleted, 0)
                .eq(TShipForecast::getTransportShipId, transportShipId)
                .last("limit 1");
        TShipForecast tShipForecast = baseMapper.selectOne(queryWrapper);
        return !Func.isNull(tShipForecast);
    }
}
